package larrys.pomodoro.domain.service;

import java.util.Collection;
import java.util.List;

import larrys.pomodoro.domain.entity.Activity;
import larrys.pomodoro.domain.entity.Round;
import larrys.pomodoro.domain.repository.ActivityRepository;
import larrys.pomodoro.domain.repository.RoundRepository;
import larrys.pomodoro.util.AssertUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ActivityService {

	private static Log logger = LogFactory.getLog(ActivityService.class);

	@Autowired
	private ActivityRepository activityRepo;

	@Autowired
	private RoundRepository roundRepo;

	public Collection<Activity> getAllActivitiesByUserId(long userId) {
		logger.debug("Trying to get all activities for PomodoroUser[id:"
				+ userId + "]");

		Collection<Activity> activities = activityRepo.getActivitiesByUserId(
				userId, false);

		logger.debug("Returning:" + activities);
		return activities;
	}

	@Transactional
	public void AddActivies(List<Activity> activities) {
		logger.debug("Trying to add :" + activities);

		for (Activity activity : activities) {
			activityRepo.addActivity(activity);
		}

		logger.debug("Activities added successfully");
	}

	public Activity getActivityById(long id) {
		logger.debug("Trying to get Activity by Activity[id:" + id + "]");

		Activity activity = activityRepo.getActivityById(id);

		logger.debug("Returning: " + activity);
		return activity;
	}

	@Transactional
	public void deleteActivity(long id) {
		logger.debug("Trying to delete Activity[id:" + id + "]");

		Collection<Round> related = roundRepo.getActivityRelatedRound(id);
		if (related.size() == 0) {
			activityRepo.realDeleteActivity(id);
		} else {
			activityRepo.markActivityDeleted(id);
		}

		logger.debug("Finished delete Activity[id:" + id + "]");
	}

	@Transactional
	public void finishActivity(long id) {
		logger.debug("Trying to finish Activity[id:" + id + "]");

		activityRepo.markActivityFinished(id);

		logger.debug("Finished finish Activity[id:" + id + "]");
	}

	@Transactional
	public void addActivityComment(long activityId, String comment) {
		AssertUtil.validId(activityId);
		logger.debug("Trying to add comment for Activity[id:" + activityId
				+ ", comment: " + comment + "]");

		Activity activity = activityRepo.getActivityById(activityId);
		activity.setComment(comment);

		activityRepo.updateActivity(activity);
		logger.debug("Finished to add comment for Activity[id:" + activityId
				+ ", comment:" + comment + "]");
	}

}
